package master;

import endereco.Enderecos;
import endereco.EnderecosDao;
import forn.Fornecedores;
import forn.FornecedoresDao;
import forn.FornecedoresXml;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.xml.bind.JAXBException;
import jaxb.CaminhoXml;
import nfe.Nfe;
import nfe.NfeDao;
import nfe.NfeXml;
import nfeitens.NfeItens;
import nfeitens.NfeItensDao;
import nfeitens.NfeItensxml;
import nftot.NotaFiscalTotalDao;
import produto.Produto;
import sysAutoNum.SysAutoNum;
import sysAutoNum.SysAutoNumDao;
import util.Renderer;
import util.Util;

/**
 *
 * @author camilo
 */
public final class Master extends javax.swing.JFrame {

  /**
   * define o model da tabela
   */
  NfeItensTableModel nfeitm = new NfeItensTableModel();
  Renderer rend = new Renderer();
  List<NfeItens> nfeItens;
  SysAutoNum sysAutoNum;
  Fornecedores forn;
  NfeItensxml nfeiXml;
  /**
   *
   */
  public Produto prod;
  private String caminho;

  /**
   * Creates new form jfMaster
   */
  public Master() {
    initComponents();
    setLocationRelativeTo(null);
    /**
     * Define o ícone para o JFrame
     */
    ImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource("imagens/mime_xml.png"));
    this.setIconImage(icon.getImage());
    this.limpar();
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do
   * NOT modify this code. The content of this method is always regenerated by the Form
   * Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();
    jLabel6 = new javax.swing.JLabel();
    jLabel7 = new javax.swing.JLabel();
    jLabel8 = new javax.swing.JLabel();
    jLabel9 = new javax.swing.JLabel();
    jtfId = new javax.swing.JTextField();
    jcbDocumento = new javax.swing.JComboBox();
    jtfNumNota = new javax.swing.JTextField();
    jTextField3 = new javax.swing.JTextField();
    jtfSerie = new javax.swing.JTextField();
    jftfDataEmissao = new javax.swing.JFormattedTextField();
    jftfDataEntrada = new javax.swing.JFormattedTextField();
    jButton1 = new javax.swing.JButton();
    jlCodForn = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jtpObs = new javax.swing.JTextPane();
    jlNomeForn = new javax.swing.JLabel();
    jScrollPane2 = new javax.swing.JScrollPane();
    jtNfeItens = new javax.swing.JTable();
    jPanel2 = new javax.swing.JPanel();
    jLabel11 = new javax.swing.JLabel();
    jLabel12 = new javax.swing.JLabel();
    jLabel13 = new javax.swing.JLabel();
    jLabel14 = new javax.swing.JLabel();
    jLabel15 = new javax.swing.JLabel();
    jLabel16 = new javax.swing.JLabel();
    jLabel17 = new javax.swing.JLabel();
    jLabel18 = new javax.swing.JLabel();
    jLabel19 = new javax.swing.JLabel();
    jLabel20 = new javax.swing.JLabel();
    jLabel21 = new javax.swing.JLabel();
    jtfBaseIcms = new javax.swing.JTextField();
    jtfIcmsS = new javax.swing.JTextField();
    jtfTotProd = new javax.swing.JTextField();
    jtfFrete = new javax.swing.JTextField();
    jtfIcms = new javax.swing.JTextField();
    jtfBaseIcmsS = new javax.swing.JTextField();
    jtfSeguro = new javax.swing.JTextField();
    jtfOutras = new javax.swing.JTextField();
    jtfDesc = new javax.swing.JTextField();
    jtfIpi = new javax.swing.JTextField();
    jtfTotNf = new javax.swing.JTextField();
    jPanel3 = new javax.swing.JPanel();
    jbValidar = new javax.swing.JButton();
    jbExportar = new javax.swing.JButton();
    jbExcluirItem = new javax.swing.JButton();
    jlStatus = new javax.swing.JLabel();
    jpStatus = new javax.swing.JProgressBar();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    jmiAbrir = new javax.swing.JMenuItem();
    jMenu2 = new javax.swing.JMenu();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Utilitário para importação de arquivos XML");
    setBackground(new java.awt.Color(254, 254, 254));
    setResizable(false);

    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Identificação"));

    jLabel1.setText("Id");

    jLabel2.setText("Documento");

    jLabel3.setText("Série");

    jLabel4.setText("Data Emissão");

    jLabel5.setText("Fornecedor:");

    jLabel6.setText("Nº da Nota");

    jLabel7.setText("CFOP");

    jLabel8.setText("Data Entrada");

    jLabel9.setText("Observações");

    jcbDocumento.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "NFEE", "NFEE3", "NFCM" }));

    jTextField3.setText("5102");

    jtfSerie.setText("001");

    try {
      jftfDataEmissao.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
    } catch (java.text.ParseException ex) {
      ex.printStackTrace();
    }

    try {
      jftfDataEntrada.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
    } catch (java.text.ParseException ex) {
      ex.printStackTrace();
    }

    jButton1.setText("Selecionar");

    jlCodForn.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jlCodForn.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));

    jtpObs.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
    jScrollPane1.setViewportView(jtpObs);

    jlNomeForn.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jlNomeForn.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel1Layout.createSequentialGroup()
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(jScrollPane1)
          .addComponent(jLabel9)
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel1)
              .addComponent(jtfId, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(4, 4, 4)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel2)
              .addComponent(jcbDocumento, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel6)
              .addComponent(jtfNumNota, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel7)
              .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jtfSerie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jftfDataEmissao, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jftfDataEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel8)))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
              .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
              .addComponent(jlCodForn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jButton1)
              .addComponent(jlNomeForn, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE))))
        .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel1Layout.createSequentialGroup()
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(jLabel1)
            .addComponent(jLabel2)
            .addComponent(jLabel6)
            .addComponent(jLabel7)
            .addComponent(jLabel3)
            .addComponent(jLabel4)
            .addComponent(jLabel8))
          .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(jLabel5)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(jlCodForn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
          .addComponent(jtfId)
          .addComponent(jcbDocumento)
          .addComponent(jtfNumNota)
          .addComponent(jTextField3)
          .addComponent(jtfSerie)
          .addComponent(jftfDataEmissao)
          .addComponent(jftfDataEntrada)
          .addComponent(jlNomeForn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jLabel9)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    jtNfeItens.setModel(nfeitm);
    /**Desabilita o ajuste automático da largura das colunas*/
    jtNfeItens.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    /** ajusta a largura das colunas*/
    jtNfeItens.getColumnModel().getColumn(0).setPreferredWidth(30);
    jtNfeItens.getColumnModel().getColumn(1).setPreferredWidth(50);
    jtNfeItens.getColumnModel().getColumn(2).setPreferredWidth(100);
    jtNfeItens.getColumnModel().getColumn(3).setPreferredWidth(300);
    jtNfeItens.getColumnModel().getColumn(4).setPreferredWidth(50);
    jtNfeItens.getColumnModel().getColumn(5).setPreferredWidth(50);
    jtNfeItens.getColumnModel().getColumn(6).setPreferredWidth(50);
    jtNfeItens.getColumnModel().getColumn(7).setPreferredWidth(50);
    jtNfeItens.getColumnModel().getColumn(8).setPreferredWidth(50);
    jtNfeItens.getColumnModel().getColumn(9).setPreferredWidth(50);
    jtNfeItens.getColumnModel().getColumn(10).setPreferredWidth(50);
    jtNfeItens.getColumnModel().getColumn(11).setPreferredWidth(50);
    jtNfeItens.getColumnModel().getColumn(12).setPreferredWidth(50);
    jtNfeItens.getColumnModel().getColumn(13).setPreferredWidth(50);
    jtNfeItens.getColumnModel().getColumn(14).setPreferredWidth(50);
    jtNfeItens.getColumnModel().getColumn(15).setPreferredWidth(50);
    jtNfeItens.getColumnModel().getColumn(16).setPreferredWidth(50);
    /**Vai para a classe Renderer pré-formatada*/
    jtNfeItens.setDefaultRenderer(jtNfeItens.getColumnClass(1), rend);
    jtNfeItens.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtNfeItensKeyPressed(evt);
      }
    });
    jScrollPane2.setViewportView(jtNfeItens);

    jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Totais"));

    jLabel11.setText("Base ICMS");

    jLabel12.setText("Valor ICMS");

    jLabel13.setText("Seguro");

    jLabel14.setText("Total NF");

    jLabel15.setText("Base ICMS S");

    jLabel16.setText("ICMS Sub");

    jLabel17.setText("Desc");

    jLabel18.setText("Outras");

    jLabel19.setText("Total Prod.");

    jLabel20.setText("Frete");

    jLabel21.setText("Valor IPI");

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
      jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel2Layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jLabel11)
          .addComponent(jtfBaseIcms, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jLabel12)
          .addComponent(jtfIcms, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(13, 13, 13)
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jLabel15)
          .addComponent(jtfBaseIcmsS, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(18, 18, 18)
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jtfIcmsS, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jLabel16))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jtfFrete, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jLabel20))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jtfSeguro, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jLabel13))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jtfOutras, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jLabel18))
        .addGap(18, 18, 18)
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jtfDesc, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jLabel17))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jLabel21)
          .addComponent(jtfIpi, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(26, 26, 26)
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jLabel19)
          .addComponent(jtfTotProd, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jtfTotNf, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jLabel14))
        .addContainerGap(38, Short.MAX_VALUE))
    );
    jPanel2Layout.setVerticalGroup(
      jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel2Layout.createSequentialGroup()
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
          .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(jLabel14)
            .addGap(6, 6, 6)
            .addComponent(jtfTotNf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(jLabel19)
            .addGap(6, 6, 6)
            .addComponent(jtfTotProd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(jLabel21)
            .addGap(6, 6, 6)
            .addComponent(jtfIpi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(jLabel17)
            .addGap(6, 6, 6)
            .addComponent(jtfDesc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(jLabel18)
            .addGap(6, 6, 6)
            .addComponent(jtfOutras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(jLabel13)
            .addGap(6, 6, 6)
            .addComponent(jtfSeguro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(jLabel20)
            .addGap(6, 6, 6)
            .addComponent(jtfFrete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(jLabel16)
            .addGap(6, 6, 6)
            .addComponent(jtfIcmsS, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(jLabel15)
            .addGap(6, 6, 6)
            .addComponent(jtfBaseIcmsS, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(jLabel12)
            .addGap(6, 6, 6)
            .addComponent(jtfIcms, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(jLabel11)
            .addGap(6, 6, 6)
            .addComponent(jtfBaseIcms, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        .addGap(0, 6, Short.MAX_VALUE))
    );

    jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));

    jbValidar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/task-complete.png"))); // NOI18N
    jbValidar.setText("Validar");

    jbExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/vcs-locally-modified.png"))); // NOI18N
    jbExportar.setMnemonic('x');
    jbExportar.setText("Exportar");
    jbExportar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbExportarActionPerformed(evt);
      }
    });

    jbExcluirItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/dialog-error.png"))); // NOI18N
    jbExcluirItem.setText("Excluir Item");
    jbExcluirItem.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbExcluirItemActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
    jPanel3.setLayout(jPanel3Layout);
    jPanel3Layout.setHorizontalGroup(
      jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel3Layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jbValidar)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jbExportar)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jbExcluirItem)
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbExcluirItem, jbExportar, jbValidar});

    jPanel3Layout.setVerticalGroup(
      jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel3Layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jbValidar)
          .addComponent(jbExportar)
          .addComponent(jbExcluirItem))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    jlStatus.setText("Pronto");
    jlStatus.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
    jlStatus.setBorder(javax.swing.BorderFactory.createEtchedBorder());

    jpStatus.setStringPainted(true);

    jMenu1.setText("Arquivo");

    jmiAbrir.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
    jmiAbrir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/folder-open.png"))); // NOI18N
    jmiAbrir.setText("Abrir");
    jmiAbrir.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jmiAbrirActionPerformed(evt);
      }
    });
    jMenu1.add(jmiAbrir);

    jMenuBar1.add(jMenu1);

    jMenu2.setText("Sair");
    jMenuBar1.add(jMenu2);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
          .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
          .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jpStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jlStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
          .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jlStatus)
          .addComponent(jpStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void jmiAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiAbrirActionPerformed
    try {
      Master.setMessageStatus("Escolha o arquivo xml...");
      ThreadXml txml = new ThreadXml();
      txml.start();
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, e.getMessage());
    }
  }//GEN-LAST:event_jmiAbrirActionPerformed

  private void jbExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbExportarActionPerformed
    Nfe nfe = new Nfe();
    NfeItens nfei = new NfeItens();
    this.addNfeItens(nfe, nfei);
  }//GEN-LAST:event_jbExportarActionPerformed

  private void jbExcluirItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbExcluirItemActionPerformed
    removeLinha();
  }//GEN-LAST:event_jbExcluirItemActionPerformed

  private void jtNfeItensKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtNfeItensKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_F12) {
      Integer lin = jtNfeItens.getSelectedRow();
      new JdPesquisaProd(this, true).setVisible(true);
    }
  }//GEN-LAST:event_jtNfeItensKeyPressed
  /**
   *
   * @param caminho
   * @param nfe
   * @return
   * @throws JAXBException
   * @throws ParseException
   * @throws SQLException
   */
  public List<NfeItens> getNfeItens(String caminho, Nfe nfe) throws JAXBException,
          ParseException, SQLException {
    nfeItens = new NfeItensxml().setClasseNfe(caminho, nfe);
    return nfeItens;
  }

  /**
   * Essa classe interna permite que o xml seja processado sem travar a 
   * interface grafica da classe Master
   */
  class ThreadXml extends Thread {

    @Override
    public void run() {
      try {
        importaXml();
      } catch (JAXBException | ParseException | SQLException ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
      }
    }
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /*
     * Set the Nimbus look and feel
     */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
     * If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. For details
     * see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(Master.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        new Master().setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton jButton1;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel11;
  private javax.swing.JLabel jLabel12;
  private javax.swing.JLabel jLabel13;
  private javax.swing.JLabel jLabel14;
  private javax.swing.JLabel jLabel15;
  private javax.swing.JLabel jLabel16;
  private javax.swing.JLabel jLabel17;
  private javax.swing.JLabel jLabel18;
  private javax.swing.JLabel jLabel19;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel20;
  private javax.swing.JLabel jLabel21;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel5;
  private javax.swing.JLabel jLabel6;
  private javax.swing.JLabel jLabel7;
  private javax.swing.JLabel jLabel8;
  private javax.swing.JLabel jLabel9;
  private javax.swing.JMenu jMenu1;
  private javax.swing.JMenu jMenu2;
  private javax.swing.JMenuBar jMenuBar1;
  private javax.swing.JPanel jPanel1;
  private javax.swing.JPanel jPanel2;
  private javax.swing.JPanel jPanel3;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JScrollPane jScrollPane2;
  private javax.swing.JTextField jTextField3;
  private javax.swing.JButton jbExcluirItem;
  private javax.swing.JButton jbExportar;
  private javax.swing.JButton jbValidar;
  private javax.swing.JComboBox jcbDocumento;
  private javax.swing.JFormattedTextField jftfDataEmissao;
  private javax.swing.JFormattedTextField jftfDataEntrada;
  private javax.swing.JLabel jlCodForn;
  private javax.swing.JLabel jlNomeForn;
  public static javax.swing.JLabel jlStatus;
  private javax.swing.JMenuItem jmiAbrir;
  public static javax.swing.JProgressBar jpStatus;
  public javax.swing.JTable jtNfeItens;
  private javax.swing.JTextField jtfBaseIcms;
  private javax.swing.JTextField jtfBaseIcmsS;
  private javax.swing.JTextField jtfDesc;
  private javax.swing.JTextField jtfFrete;
  private javax.swing.JTextField jtfIcms;
  private javax.swing.JTextField jtfIcmsS;
  private javax.swing.JTextField jtfId;
  private javax.swing.JTextField jtfIpi;
  private javax.swing.JTextField jtfNumNota;
  private javax.swing.JTextField jtfOutras;
  private javax.swing.JTextField jtfSeguro;
  private javax.swing.JTextField jtfSerie;
  private javax.swing.JTextField jtfTotNf;
  private javax.swing.JTextField jtfTotProd;
  private javax.swing.JTextPane jtpObs;
  // End of variables declaration//GEN-END:variables

  /**
   *
   * @param msg
   */
  public static void setMessageStatus(String msg) {
    jlStatus.setText(" Status: " + msg);
  }

  private void setJtNfeItensTM(List<NfeItens> nfei) {
    while (nfeitm.getRowCount() > 0) {
      nfeitm.remove(0);
    }
    if (nfei.isEmpty()) {
      JOptionPane.showMessageDialog(null, "Nenhum registro encontrado!",
              "ATENÇÃO", JOptionPane.ERROR_MESSAGE);
    } else {
      nfeitm.adicionaLista(nfei);
      jpStatus.setIndeterminate(false);
      setMessageStatus("Concluído!");
    }
  }

  /**
   * Executa rotina para
   *
   * @throws JAXBException
   * @throws ParseException
   * @throws SQLException
   */
  public void importaXml() throws JAXBException, ParseException, SQLException {

    //      Captura o caminho e nome do arquivo XML
    caminho = CaminhoXml.getCaminhoXml();

    if (caminho != "") {
      jpStatus.setVisible(true);
      jpStatus.setValue(0);
      //      preenche o jtext field
      Nfe nfe = new Nfe();
      NfeXml nfeXml = new NfeXml();
      SysAutoNumDao san = new SysAutoNumDao();
      FornecedoresDao fdao = new FornecedoresDao();
      FornecedoresXml fxml = new FornecedoresXml();

      /**
       * if (new NfeXml().setClasseNfe(caminho, nfe) == null) { jpStatus.setValue(0);
       * return; }
       */
      new NfeXml().setClasseNfe(caminho, nfe);

      /**
       * busca informações no BD para definir o id do registro
       */
      sysAutoNum = san.getAutoNum("NotaFiscal");
      Integer san2 = sysAutoNum.getContador();
      san2++;
      jtfId.setText(san2.toString());
      /**
       * busca informações no BD para definir o fornecedor
       */
      forn = fdao.getForn(nfe.getEntidade());
      if (forn.getId() == null) { // verifica se o fornecedor está cadastrado
        /**
         * Pergunta ao usuário se ele deseja cadastrar com as informações do XML
         */
        Master.setMessageStatus("Fornecedor nao cadastrado...");
        Integer esc = JOptionPane.showConfirmDialog(null, "Deseja cadastrar o fornecedor com as informações\n"
                + "do arquivo XML?",
                "Fornecedor não cadastrado!", JOptionPane.YES_NO_OPTION);
        if (esc == JOptionPane.YES_OPTION) { // Executa o código abaixo se o usuário escolher "SIM"
          EnderecosDao edao = new EnderecosDao();
          SysAutoNum sanf = new SysAutoNum();
          sanf = san.getAutoNum("Fornecedores");
          Integer sanf1 = sanf.getContador();
          sanf1++;
          forn.setId(sanf1.toString());
          forn.setCnpj(fxml.getCnpj(caminho));
          forn.setIe(fxml.getIe(caminho));
          forn.setRazaoSocial(fxml.getRazaoSocial(caminho));
          forn.setNomeFantasia(fxml.getNomeFantasia(caminho));
          fdao.adicionar(forn);

          Enderecos e = new Enderecos();
          e.setIdEntidade(forn.getId());
          e.setEndereco(fxml.getLograd(caminho));
          e.setNumero(fxml.getNro(caminho));
          e.setComplemento(fxml.getComp(caminho));
          e.setBairro(fxml.getBairro(caminho));
          e.setMunicipio(Integer.parseInt(fxml.getMunCod(caminho)));
          e.setUf(fxml.getUf(caminho));
          e.setCep(fxml.getcep(caminho));
          e.setFone(fxml.getFone(caminho));
          e.setNmMunicipio(fxml.getMunNome(caminho));
          edao.adicionar(e);
          san.altera("Fornecedores");

          jlCodForn.setText(forn.getId());
          jlNomeForn.setText(forn.getNomeFantasia());
        } else { // Se o usuário não efetuar o cadastro, abandona a execução do código
          limpar();
          return;
        }
      } else {
        jlCodForn.setText(forn.getId());
        jlNomeForn.setText(forn.getNomeFantasia());
      }

      jtfNumNota.setText(nfe.getNumeroDocumento().toString());
      jtfSerie.setText(nfe.getSerie());
      jftfDataEmissao.setText(new Util().formatData(nfe.getDataEmissao()));

      if (nfe.getDataEntrada() != null) {
        jftfDataEntrada.setText(new Util().formatData(nfe.getDataEntrada()));
      } else {
        jftfDataEntrada.setText(new Util().formatData(new Date(System.currentTimeMillis())));
      }

      jtpObs.setText(nfe.getObservacao());
      jtfBaseIcms.setText(new Util().formatNumSql(nfe.getBaseICMS()));
      jtfIcms.setText(new Util().formatNumSql(nfe.getValorICMS()));
      jtfBaseIcmsS.setText(new Util().formatNumSql(nfe.getBaseICMSsub()));
      jtfIcmsS.setText(new Util().formatNumSql(nfe.getValorICMSsub()));
      jtfTotProd.setText(new Util().formatNumSql(nfe.getValorProdutos()));
      jtfTotNf.setText(new Util().formatNumSql(nfe.getValorNota()));
      jtfFrete.setText(new Util().formatNumSql(nfe.getValorFrete()));
      jtfSeguro.setText(new Util().formatNumSql(nfe.getValorSeguro()));
      jtfOutras.setText(new Util().formatNumSql(nfe.getValorOutras()));
      jtfDesc.setText(new Util().formatNumSql(nfe.getValorDesconto()));
      jtfIpi.setText(new Util().formatNumSql(nfe.getValorIPI()));

      setJtNfeItensTM(getNfeItens(caminho, nfe));
    }
    setMessageStatus("Importação concluída!");
  }

  /**
   * Adiciona os dados gravados nos objetos e os repassa para os devidos campos para
   * visualização e alteração por parte do usuário.
   *
   * @param nfe
   * @param nfei
   */
  public void addNfeItens(Nfe nfe, NfeItens nfei) {
    try {
      nfe.setID(Integer.parseInt(jtfId.getText()));
      nfe.setDocumento(jcbDocumento.getSelectedItem().toString());
      nfe.setSerie(jtfSerie.getText());
      nfe.setNumeroDocumento(Double.parseDouble(jtfNumNota.getText()));
      nfe.setEntidade(jlCodForn.getText());
      nfe.setDataEmissao(new Util().formatDataSToD(jftfDataEmissao.getText()));
      nfe.setDataEntrada(new Util().formatDataSToD(jftfDataEntrada.getText()));
      nfe.setBaseICMS(Float.parseFloat(jtfBaseIcms.getText()));
      nfe.setValorICMS(Float.parseFloat(jtfIcms.getText()));
      nfe.setBaseICMSsub(Float.parseFloat(jtfBaseIcmsS.getText()));
      nfe.setValorICMSsub(Float.parseFloat(jtfIcmsS.getText()));
      nfe.setValorFrete(Float.parseFloat(jtfFrete.getText()));
      nfe.setValorSeguro(Float.parseFloat(jtfSeguro.getText()));
      nfe.setValorOutras(Float.parseFloat(jtfOutras.getText()));
      nfe.setValorIPI(Float.parseFloat(jtfIpi.getText()));
      nfe.setValorProdutos(Float.parseFloat(jtfTotProd.getText()));
      nfe.setValorNota(Float.parseFloat(jtfTotNf.getText()));
      nfe.setObservacao(jtpObs.getText());
      nfe.setDataCadastro(new Date(System.currentTimeMillis()));
      nfe.setValorDesconto(Float.parseFloat(jtfDesc.getText()));

      NfeDao nfedao = new NfeDao();
      NotaFiscalTotalDao nftdao = new NotaFiscalTotalDao();
      NfeItensDao nfeidao = new NfeItensDao();

      nfedao.adicionar(nfe);
      nftdao.adicionar(nfe);
      nfeidao.adicionar(nfeitm, nfe);

      new SysAutoNumDao().altera("NotaFiscal");
      JOptionPane.showMessageDialog(null, "Exportação realizada com sucesso!",
              "", JOptionPane.INFORMATION_MESSAGE);
      limpar();
    } catch (SQLException | ParseException e) {
      JOptionPane.showMessageDialog(null, e.getMessage());
    }
  }

  /**
   * Método para apagar todo o conteúdo ativo em caixas de textos e outras listas
   */
  public void limpar() {
    if (nfeitm.getRowCount() != 0) {
      nfeitm.limpaLista();
    }
    jtfId.setText(null);
    jtfNumNota.setText(null);
    jftfDataEmissao.setText(null);
    jftfDataEntrada.setText(null);
    jlCodForn.setText(null);
    jlNomeForn.setText(null);
    jtpObs.setText(null);
    jtfBaseIcms.setText(null);
    jtfIcms.setText(null);
    jtfBaseIcmsS.setText(null);
    jtfIcmsS.setText(null);
    jtfFrete.setText(null);
    jtfOutras.setText(null);
    jtfSeguro.setText(null);
    jtfDesc.setText(null);
    jtfIpi.setText(null);
    jtfTotProd.setText(null);
    jtfTotNf.setText(null);
    Master.setMessageStatus("");
    Master.jpStatus.setValue(0);
    Master.jpStatus.setVisible(false);
  }

  /**
   * Remove a linha selecionada no jTable principal <br/> <b>1º - </b> Captura a linha
   * selecionada<br/> <b>2º - </b> Remove a linha utilizando o método
   * {@link nfeitm.remove}
   */
  private void removeLinha() {
    nfeitm.remove(jtNfeItens.getSelectedRow());
  }
}